//
//  AiRoleItemView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/4/1.
//

import SwiftUI
import Kingfisher

/**
 *  ai 角色item
 */
struct ChatListItemView: View {
    @State var delTips = false
    @StateObject var viewModel = AiRoleItemViewModel()
    @State private var showContent = false
    @State private var select = false
    
    var bean:AiRoleBean
    var aiRoleOften: String? = nil
    @Binding var items:[AiRoleBean]
    
    var body: some View {
        // 目前contextMenu 会失效，先不处理，后续看下有没有更好的解决方案
        ZStack {
            Menu {
                commonMenuContent
            } label: {
                contentView
            }
        }.contextMenu {
            commonMenuContent
        }
    }
    
    
}

//内容试图
extension ChatListItemView {
    private var contentView: some View {
        HStack(alignment:.top) {
            AvatarImageView(url: bean.avatar ?? "", size: 50)
                .contentShape(Rectangle())
                .onTapGesture {
                    pathManager.jump(type: JumpType.AI_ROLE, data: bean)
                }
            VStack(alignment:.leading){
                HStack(spacing: 5) {
                    Text(bean.name ?? "").font(.system(size: 14, weight: .medium)).foregroundColor(.bgNormalText)
                    if bean.isSystem == true { //显示官方标签
                        Text("官方").font(.system(size: 8)).foregroundColor(Color.white).lineLimit(2)
                            .padding(.horizontal, 2)
                            .padding(.vertical, 1)
                            .background(themeManager.themeColor)
                            .clipShape(RoundedRectangle(cornerRadius: 3))
                    }
                }
                Text(bean.describe ?? "")
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4).lineLimit(2)
                    .multilineTextAlignment(.leading)  // 明确设置多行文本对齐方式
            }
            Spacer()
            ZStack {
                Image(.appIconArrowRight)
                    .resizable()
                    .frame(width: 15,height: 15)
            }.frame(maxHeight: .infinity, alignment: .center)
        }.frame(maxWidth: .infinity,alignment:.leading)
            .padding(EdgeInsets(top: 10, leading: 0, bottom: 10, trailing: 0))
            .contentShape(Rectangle())
            .onAppear{
                select = bean.select
            }
            .alert("温馨提示",isPresented:$delTips) {
                Button("取消",role: .cancel){}
                Button("确定",role: .destructive) {
                    viewModel.doDelete(bean: bean)
                }
            } message: {
                Text("是否确定删除该角色")
            }
            .sheet(isPresented: $showContent) {
                Text("\(bean.describe ?? "")\n\n\n\(bean.describe2 ?? "")")
                    .font(.system(size: 14))
                    .foregroundStyle(.bgNormalText2)
                    .padding()
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
            }.presentationDragIndicator(.visible)
    }
}

//菜单
extension ChatListItemView {
    // 将菜单内容抽离为一个计算属性，方便复用
    private var commonMenuContent: some View {
        Group {
            Button("查看"){
                showContent.toggle()
            }
            if bean.select {
                Button("取消选择") {
                    if items.count(where: {$0.select}) <= 1 {
                        showLog("至少选择一个")
                        showToast("至少选择一个")
                        return
                    }
                    bean.select = false
                    viewModel.selectAiRole(list: items) {
                        select = false
                        //取消选择，需要删除任务
                        TaskExt.deleteTask(bean.objectId)
                    }
                }
            } else {
                Button("选择") {
                    if items.count(where: {$0.select}) >= 5 {
                        showLog("最多只能选择5个")
                        showToast("最多只能选择5个")
                        return
                    }
                    bean.select = true
                    viewModel.selectAiRole(list: items){
                        select = true
                    }
                }
            }
            if bean.isSystem ?? false == false {
                Button("修改") {
                    pathManager.jump(type: JumpType.AI_ROLE, data: bean)
                }
            }
            if bean.isSystem ?? false == false {
                Button("删除") {
                    delTips.toggle()
                }
            }
            if aiRoleOften == bean.objectId {
                Button("取消常聊"){
                    viewModel.doSetOften(roleId: nil)
                }
            } else {
                Button("设置常聊") {
                    viewModel.doSetOften(roleId: bean.objectId)
                }
            }
            Button("聊天") {
                var param = ChatView.Param()
                param.bean = bean
                param.isMain = false
                pathManager.jump(type: JumpType.CHAT_VIEW , data: param)
            }
        }
    }
    
}

#Preview {
    @State var previewItems: [AiRoleBean] = [AiRoleBean(), AiRoleBean()]
    ChatListItemView(bean:AiRoleBean(), items: $previewItems)
}
